#pragma once
#include <iostream>
#include <cstdlib>
#include <string>
#include <unistd.h>
#include <sys/socket.h>
#include <sys/types.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include "InetAddr.hpp"
#include "Comm.hpp"


class TcpClient
{
    public:
    TcpClient(std::string ip,uint16_t port):server(port,ip)
    {}

    void Init()
    {
        _sockfd = socket(AF_INET,SOCK_STREAM,0);
        if(_sockfd < 0)
        {
            std::cout << "socket error" << std::endl;
            exit(1);
        }
        std::cout << "socket success" << std::endl;
        if(connect(_sockfd,(struct sockaddr*)&server.Addr(),server.Len()) < 0)
        {
            std::cout << "connect error" << std::endl;
            exit(1);
        }
        std::cout << "connect success" << std::endl;        
    }

    void Start()
    {
        //连接成功建立，客户端开始循环式地向服务端发送消息，接收消息
        while(true)
        {
            std::string input;
            std::getline(std::cin,input);//读取一行
            int n = write(_sockfd,input.c_str(),input.size());
            if(n <= 0)
            {
                std::cout << "write error" << std::endl;
                break;
            }
            char buffer[1024] = {0};
            int sz = read(_sockfd,buffer,sizeof(buffer) - 1);
            if(sz < 0)
            {
                std::cout << "read error" << std::endl;
                break;
            }
            else if(sz == 0)
            {
                std::cout << "server close" << std::endl;
                break;
            }
            else
            {
                buffer[sz] = 0;
                std::cout << buffer << std::endl;
            }
        }
        close(_sockfd);
    }
    ~TcpClient()
    {}

    private:
    int _sockfd;
    InetAddr server;
};